<?php 

class DefaultScheduler extends Scheduler {
	
	private $scheduledJobs;	
	private $taskManager;
	private $schedulerService;
		
	public function __construct($taskManager) {
		
		$this->taskManager = $taskManager;
		$this->schedulerService = SchedulerService::getInstance();
		
		if(!file_exists(LOCK_PATH)) {
			mkdir(LOCK_PATH);
		}
	}
	
	public function addJobs($jobs) {
		$this->scheduledJobs = $jobs;
	}
	
	public function isStandby () {
		return $this->schedulerService->isInStandbyMode();
	}
	
	public function needSchedule() {		
		$currentDate = $this->schedulerService->getBaseDate();	
		if($currentDate === false) {
			Yii::log('unable to get scheduler date', CLogger::LEVEL_ERROR, SCHEDULER_LOG);
			return false;
		}

		$maxDate = DateHelper::makeDate(time() - SCHE_OFFSET_TIME * 60);

		if($currentDate < $maxDate) {
			return DateHelper::makeDate(strtotime($currentDate) + 60);
		}
		else {
			return false;
		}
	}
	
	public function isRunning() {		
		if(!($lock_file = fopen(SCHEDULER_LOCK, 'a+'))) {
			return 'open lock_file error';
		}
		if(!flock($lock_file, LOCK_EX))	{
			fclose($lock_file);
			return 'lock lock_file error';
		}

		// use kill to check whether the scheduler is still runing
		$last_pid = intval(file_get_contents(SCHEDULER_LOCK));	
		if($last_pid > 0 && posix_kill($last_pid, 23)) {
			fclose($lock_file);
			return 'another scheduler is running';
		}
		file_put_contents(SCHEDULER_LOCK, posix_getpid());

		fclose($lock_file);
		return false;
	}
	
	public function scheduleJobs($baseDate) {
		foreach($this->scheduledJobs as $scheduleJob) {						
			$taskDate = DateHelper::previousDate(strtotime($baseDate), $scheduleJob->getFreqency());			
			if($scheduleJob->canTrigger($taskDate)) {
				$scheduleJob->createTask($taskDate);
			}
		}
		
		// clear the already scheduled jobs to release memory
		unset($this->scheduledJobs);
	}
	
	public function scheduleTasks($baseDate) {
		$this->taskManager->scheduleTasks($baseDate);
	}
	
	public function saveScheduleDate($baseDate) {
		return  $this->schedulerService->addSchedulerLog(array('date' => $baseDate));
	}
	
	public function stop() {
		
	}
}
?>
